package handlers

import (
	"github.com/gin-gonic/gin"
	"post-pic-sys/models"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	art := models.Art{
		Title:   title,
		Content: content,
	}
	tx := models.DB.Begin()
	err := tx.Create(&art).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "发布失败",
		})
		return
	} else {
		tx.Commit()
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "发布成功",
		})
		return
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	off := (page - 1) * size
	var art []models.Art
	err := models.DB.Offset(off).Limit(size).Group("created_at desc").Find(&art).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": art,
		})
		return
	}
}
func Det(c *gin.Context) {
	id := c.Query("id")
	var art models.Art
	err := models.DB.First(&art, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": art,
		})
		return
	}
}
